<?php
class XML {
    private $data;
    private $envelope;
    private $namespaces;

    function __construct($fields, $envelope = LEAVE_DEFAULT, $namespaces = LEAVE_DEFAULT) {
        $this->data = $fields;
        $this->envelope = $envelope;
        $this->namespaces = $namespaces;
    }

    private function generateXml($set = LEAVE_DEFAULT) {
        if ($set == LEAVE_DEFAULT) { $set = $this->data; }
        $result = "";
        foreach ($set as $key=>$value) {
            if (is_array($value)) {
                if (strstr($key, "[") === false) {
                    $result .= "<$key>" . $this->generateXml($value) . "</$key>";
                } else {
                    preg_match("@(.*?)\[(.*?)=(.*?)\]@", $key, $matches);
                    $tag = $matches[1];
                    $attrName = $matches[2];
                    $attrValue = $matches[3];
                    $result .= "<$tag $attrName='$attrValue'>" . $this->generateXml($value) . "</$tag>";
                }
            } else {
                if (strstr($key, "[") === false) {
                    $result .= "<$key>$value</$key>";
                } else {
                    preg_match("@(.*?)\[(.*?)=(.*?)\]@", $key, $matches);
                    $tag = $matches[1];
                    $attrName = $matches[2];
                    $attrValue = $matches[3];
                    $result .= "<$tag $attrName='$attrValue'>$value</$tag>";
                }
            }
        }
        return $result;
    }

    function __toString() {
        $result = "";
        $nslist = "";
        if ($this->envelope != LEAVE_DEFAULT) {
            foreach ($this->namespaces as $key=>$value) {
                if ($key == "base") {
                    $nslist .= " xmlns=\"$value\"";
                } else {
                    $nslist .= " xmlns:$key=\"$value\"";
                }
            }
            $result = "<?xml version='1.0' encoding='UTF-8'?>";
            $result .= "<" . $this->envelope . $nslist . ">";
        }
        $result .= $this->generateXml();
        if ($this->envelope != LEAVE_DEFAULT) {
            $result .= "</" . $this->envelope . ">";
        }
        return $result;
    }
}

?>
